package com.gis.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.gis.entity.ScriptData;
import com.gis.result.ResponseResult;
import com.gis.service.impl.ScriptServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;


@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/script")
@Tag(name = "[算法]脚本", description = "脚本数据接口")
public class ScriptController {
    @Autowired
    private ScriptServiceImpl scriptService;

    @Operation(summary = "添加脚本", description = "添加脚本")
    @PostMapping("/add_script")
    @Parameters(
        {
            @Parameter(name = "description", description = "脚本描述", required = false),
            @Parameter(name = "inputNum", description = "输入参数量", required = true),
            @Parameter(name = "outputNum", description = "输出参数量", required = true),
            @Parameter(name = "outputType", description = "输出参数类型", required = true),
            @Parameter(name = "inputType", description = "输入参数类型", required = true),
        }
    )
    public ResponseResult<HashMap<String, Object>> addScript(MultipartFile file, String description, Integer inputNum, Integer outputNum, String outputType, String inputType) {
        HashMap<String, Object> result = new HashMap<>();
        try {
            result = scriptService.addScript(file, description, inputNum, outputNum, outputType, inputType);
        } catch (Exception e) {
            e.printStackTrace();
//            result.put("msg", "添加脚本失败");
//            result.put("code", 500);
            result.put("message", e.getMessage());
            return ResponseResult.fail(result);
        }
        return ResponseResult.success(result);
    }

    @Operation(summary = "查看所有脚本")
    @GetMapping("/get_all_script")
    public ResponseResult<List<ScriptData>> getAllScript() {
        List<ScriptData> scripts = scriptService.list();
        return ResponseResult.success(scripts);
    }
    
    @Operation(summary = "添加脚本压缩包", description = "添加脚本压缩包")
    @PostMapping("/add_script_zip")
    @Parameters(
        {
            @Parameter(name = "description", description = "脚本描述", required = false),
            @Parameter(name = "inputNum", description = "输入参数量", required = true),
            @Parameter(name = "outputNum", description = "输出参数量", required = true),
            @Parameter(name = "inputNum", description = "输入参数类型", required = true),
            @Parameter(name = "outputType", description = "输出参数类型", required = true),
            @Parameter(name = "inputType", description = "输入参数类型", required = true),
        }
    )
    public ResponseResult<HashMap<String, Object>> addScriptZip(MultipartFile file, String description, Integer inputNum, Integer outputNum, String outputType, String inputType) {
        HashMap<String, Object> result = new HashMap<>();
        try {
            result = scriptService.addScriptZip(file, description, inputNum, outputNum, outputType, inputType);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("msg", "添加脚本压缩包失败");
            result.put("code", 500);
            result.put("data", e.getMessage());
            return ResponseResult.fail(result);
        }
        return ResponseResult.success(result);
    }

    @Operation(summary = "下载脚本", description = "下载脚本")
    @GetMapping("/download_script")
    @Parameters(
        {
            @Parameter(name = "scriptId", description = "脚本ID", required = true)
        }
    )
    public void downloadScript(@Parameter Integer scriptId, HttpServletResponse response) {
        ScriptData script = scriptService.getById(scriptId);
        if (script == null) {
            throw new RuntimeException("脚本不存在");
        }
        try {
            String pathName = script.getSavedDir() + "/" + script.getSavedName();
            File file = new File(pathName);
            switch (pathName.substring(pathName.lastIndexOf('.') + 1, pathName.length())) {
                case "zip":
                    response.setContentType("application/zip");
                    break;
            
                default:
                    throw new Exception("未知文件类型");
            }
            response.setHeader("Content-Disposition", "attachment; filename=" + script.getSavedName());
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                response.getOutputStream().write(buffer, 0, len);
            }
            fis.close();
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType("application/json");
            try{
                response.getOutputStream().write(("{\"msg\":\"下载脚本失败\",\"code\":500,\"data\":\"" + e.getMessage() + "\"}").getBytes());
            }catch(Exception e1){
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }

    @Operation(summary = "删除脚本", description = "删除脚本")
    @DeleteMapping("/delete_script")
    @Parameters(
        {
            @Parameter(name = "scriptId", description = "脚本ID", required = true)
        }
    )
    public ResponseResult<HashMap<String, Object>> deleteScript(@Parameter Integer scriptId) {
        HashMap<String, Object> result = new HashMap<>();
        try {
            result = scriptService.deleteScript(scriptId);
            if(result.get("result").equals(false)){
                return ResponseResult.fail(result.get("msg").toString());
            } else{
                return ResponseResult.success(result.get("msg").toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("删除脚本失败");
        }
    }


}
